/*
 * @Author: wangxing wangxing@kd.com
 * @Date: 2024-08-22 11:10:57
 * @LastEditors: wangxing wangxing@kd.com
 * @LastEditTime: 2024-08-23 16:08:02
 * @FilePath: \quick\KD-WEB-VUE-BUSINESS\static\drawio\utils\customEditCell.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
class CustomEditCell {
  constructor(graph) {
    this.inputEl = null
    this.maskEl = null
    this.graph = graph
    this.cell = graph.getSelectionCell()
    this.state = graph.getView().getState(this.cell);

    this.cellFrom = {}

    if (this.cell.style.includes('image=')) return
    if (this.cell.value instanceof Object && ['entity', 'quote'].includes(this.cell.value.nodeName)) {
      this.graph.selectionModel.clear()
      this.createEditInput()
    }
  }

  /**创建input输入框 */
  createEditInput() {
    const bound = this.graph.container.getBoundingClientRect();
    this.maskEl = document.createElement('div')
    this.maskEl.style.cssText = `
        width: ${bound.width + 4}px;
        height: ${bound.height + 4}px;
        position:absolute;
        left: ${this.graph.view.translate.x - 2}px;
        top: ${this.graph.view.translate.y - 2}px;
        zIndex: 2;
    `
    this.graph.container.appendChild(this.maskEl);

    this.inputEl = document.createElement('input')
    this.inputEl.style.cssText = `
        width: ${this.cell.geometry.width}px;
        height: ${this.cell.geometry.height}px;
        position:absolute;
        font-size: 12px;
        zIndex: 3;
        font-weight: ${this.state.style.fontStyle === 1 ? 700: 400};
        left: ${this.state.x}px;
        top: ${this.state.y}px;
        background-color: ${this.state.style.fillColor || '#dae8fc'};
        background-image: none;
        border: 1px solid ${this.state.style.strokeColor || '#000'};
        text-align: center;
        color: #000;
        box-sizing: border-box;
        display: inline-block;
        outline: none;
        padding: 0 3px;
        transition: border-color .2s cubic-bezier(.645,.045,.355,1);
        box-shadow: 0 0 8px 0 rgb(232 237 250 / 60%), 0 2px 4px 0 rgb(232 237 250 / 50%);
    `
    this.graph.container.appendChild(this.inputEl);

    this.setDefaultValue()

    this.installListeners()
  }

  /**填充默认值 */
  async setDefaultValue() {
    const cellParams = resolveCell(this.cell)
    const params = {
      modelId: cellParams.modelId,
      eObjectId: cellParams.eObjectId,
      objectId: cellParams.objectId,
      name: cellParams.name,
      pageObjNum: cellParams.pageObjNum,
      xuqiuId: cellParams.xuqiuId,
      identityCode: cellParams.identityCode,
    };
    if (!window.top.MODELID) return
    const res = await window.$axios.get(window.top.g.ApiUrl2 + '/object/editGraphObject', {
      params
    })
    // 根据类型分组
    res.data.attributeTab.forEach(item => {
      if (Array.isArray(item.objectFormList) && item.objectFormList.length && item.type === 'basic') {
        const row = item.objectFormList.find(i => i.attrKey === 'name')
        if (row) {
          this.cellFrom = res.data.form || {}

          this.inputEl.value = row.attrValueObject
          this.inputEl.select()
          this.inputEl.focus()
        }
      }
    });
  }

  /**注册事件 */
  installListeners() {
    this.maskEl.addEventListener('click', (e) => {
      this.confirm()
    })

    this.inputEl.addEventListener('click', (e) => {
      e.stopPropagation()
    })

    this.inputEl.addEventListener('keydown', (e) => {
      if (e.keyCode === 13) {
        // this.confirm()
      }
      if (e.ctrlKey && e.code === 'KeyA') {
        this.inputEl.select()
      }
      e.stopPropagation()
    })

    this.inputEl.addEventListener('keyup', (e) => {
      e.stopPropagation()
    })

    this.inputEl.addEventListener('keypress', (e) => {
      e.stopPropagation()
    })

    this.inputEl.addEventListener('mousedown', (e) => {
      e.stopPropagation()
    })
    this.inputEl.addEventListener('mouseup', (e) => {
      e.stopPropagation()
    })
  }

  /** */
  confirm() {
    const validate = new Promise((resolve) => {
      const value = this.inputEl.value
      if (!value) {
        this.inputEl.style.border = '1px solid red';
        window.top.$Message({
          type: 'warning',
          message: '请输入名称'
        })
      } else {
        this.inputEl.style.border = '1px solid #dcdfe6';
      }
      resolve(value);
    })

    validate.then(value => {
      if (value) {
        const cellParams = resolveCell(this.cell)
        const fromData = {
          ...this.cellFrom,
          name: value,
          objectId: cellParams.objectId,
          objectXml: myEditor.editor.getXmlByCellObjectId(this.cell),
        }

        const getUpdateGraphObjectApi = async (updateGraphObject) => {
          // 保存xml
          updateGraphObject({
            ...fromData,
          }, cellParams).then(res => {
            if (res.statusCode === 200) {
              if (res.data.label !== null && res.data.label !== undefined) {
                this.cell.objectLabel = res.data.label
              }
              window.disableRefreshAttribute = true;
              window.updateCellAttribute(this.cell, this.graph, res.data);
              window.disableRefreshAttribute = false;
              this.destroy()
            }
          });
        }
        window.top.$store.state.bus.drawioBus.$emit('getUpdateGraphObjectApi', getUpdateGraphObjectApi)
      }
    })

  }

  /**销毁 */
  destroy() {
    console.log('destroy');
    if (this.maskEl != null) {
      this.maskEl.parentNode && this.maskEl.parentNode.removeChild(this.maskEl);
      this.maskEl = null;
    }
    if (this.inputEl != null) {
      this.inputEl.parentNode && this.inputEl.parentNode.removeChild(this.inputEl);
      this.inputEl = null;
    }
  }
}
